package com.spark.tags;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkConfiguration;
import com.spark.core.SparkContext;
import com.spark.core.XMap;
import com.spark.util.CookieHelper;

import freemarker.template.TemplateModelException;

/**
 * Screen标签.
 * 
 * @version $Id: Screen.java v 1.0 2010-12-10 下午01:39:43 IBM Exp $
 * @author <a href="mailto:njq.niu@hand-china.com">vincent</a>
 */
public class Screen extends SparkTag {
	
	public static final String PROPERTITY_TITLE = "title";
	
	private static final String DEFAULT_TEMPLATES = "screen.ftl";
	private static final String DEFAULT_THEME = "default";
	
	private static final String PROPERTITY_TEMPLATE = "template";

	public String execute(XMap view, SparkContext context) throws Exception {
		StringBuilder sb = new StringBuilder();
		List<XMap> children = view.getChilds();
		if (children != null) {
			Iterator<XMap> it = children.iterator();
			while (it.hasNext()) {
				XMap child = it.next();
				sb.append(SparkBuilder.build(child, context));
			}
		}
		
		context.put("title", view.getString(PROPERTITY_TITLE,""));
		context.put("content", sb.toString());
		context.put("stylesheet", generateStyleSheet(context));
		context.put("javascript", generateJavaScript(context));
			
		processRequestClient(context);
		return super.build(context, getTemplate(view));
	}
	
	private String getTemplate(XMap view){
		String tpl = view.getString(PROPERTITY_TEMPLATE);
		return tpl == null ? DEFAULT_TEMPLATES : tpl;
	}
	
	
	private void processRequestClient(SparkContext context){
		HttpServletRequest request = context.getRequest();
		String userAgent = request.getHeader("User-Agent");
		if(userAgent!=null){
			StringBuilder sb = new StringBuilder();
			userAgent = userAgent.toLowerCase();
			boolean isWin7 = userAgent.indexOf("windows nt 6.1") != -1;
//			boolean isWinXP = userAgent.indexOf("windows nt 5.1") != -1;
			boolean isChrome = userAgent.indexOf("chrome") != -1;
			boolean isMaxThon = userAgent.indexOf("maxthon") != -1; 
			boolean isSafari = userAgent.indexOf("safari") != -1; 
			if(isWin7 && (isChrome||isMaxThon)){
				sb.append(createFontSizeAdjustStyle());
			}
//			sb.append("body,input, button,textarea {font-size:");
//			if(isWin7 || isSafari){
//				sb.append(12);
//			}else{
//				sb.append(12);
//			}
//			sb.append("px}");
			context.put("defaultStyleSheet", sb.toString());
		}
	}
	
	private String createFontSizeAdjustStyle(){
		return "html,body{-webkit-text-size-adjust:none;}";
	}

	private String generateStyleSheet(SparkContext context) {
		List<String> sheets = context.getStyleSheet();
		String theme = CookieHelper.getCookieValue(context.getRequest(),"theme");
		if (theme == null)
			theme = DEFAULT_THEME;
		
		
		
		StringBuilder sb = new StringBuilder();
		//TODO:性能测试注释
		Iterator<String> it = sheets.iterator();
		while (it.hasNext()) {
			String styleSheet = it.next();
//			String filePath = "/resources/"+theme+"/"+styleSheet;
//			File file = new File(context.getServletConfig().getServletContext().getRealPath(filePath));
//			sb.append("<link href=\"").append(context.getContextPath()).append("/resources/").append(theme).append("/").append(styleSheet).append("?v=").append(file.lastModified()).append("\" rel=\"stylesheet\" type=\"text/css\"/>");
			sb.append("<link href=\"").append(context.getContextPath()).append("/resources/").append(theme).append("/").append(styleSheet).append("\" rel=\"stylesheet\" type=\"text/css\"/>");
			if(it.hasNext()){
				sb.append("\n");
			}
		}
		return sb.toString();
	}
	
	private String generateJavaScript(SparkContext context) {
		List<String> scripts = context.getJavaScript();

		String theme = CookieHelper.getCookieValue(context.getRequest(),"theme");
		if (theme == null)
			theme = DEFAULT_THEME;

		StringBuilder sb = new StringBuilder();
		//TODO:性能测试注释
		Iterator<String> it = scripts.iterator();
		while (it.hasNext()) {
			String script = it.next();
//			String filePath = "/resources/"+theme+"/"+script;
//			File file = new File(context.getServletConfig().getServletContext().getRealPath(filePath));
//			sb.append("<script src=\"").append(context.getContextPath()).append("/resources/").append(theme).append("/").append(script).append("?v=").append(file.lastModified()).append("\" type=\"text/javascript\"></script> ");
			sb.append("<script src=\"").append(context.getContextPath()).append("/resources/").append(theme).append("/").append(script).append("\" type=\"text/javascript\"></script> ");
			if(it.hasNext()){
				sb.append("\n");
			}
		}
		return sb.toString();
	}
	
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context) throws TemplateModelException {
		HttpServletRequest request = context.getRequest();
		String xrequest = request.getHeader(SparkConfiguration.X_REQUESTED_WITH);
		Map map = context.getFreeMarkerModel();
		StringBuilder sb = new StringBuilder();
		if(!SparkConfiguration.XML_HTTP_REQUEST.equals(xrequest)) {
			sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r");
			sb.append("<html xmlns=\"http://www.w3c.org/1999/xhtml\">\r");
		}
		sb.append("<head>\r");
		if(!SparkConfiguration.XML_HTTP_REQUEST.equals(xrequest)) {
			sb.append("<title>").append(get(map,"title")).append("</title>\r");
			sb.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=9\" />\r");
			sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\r");
			sb.append(get(map,"stylesheet")).append(" \r");
		}
		sb.append("<link href=\"").append(context.getContextPath()).append("/css/default.css\" rel=\"stylesheet\" type=\"text/css\"></link>\r");
		sb.append(get(map,"javascript"));
		sb.append("<script src=\"").append(context.getContextPath()).append("/js/default.js\" type=\"text/javascript\"> </script>\r");
		sb.append("<style>\r");
		sb.append(get(map,"defaultStyleSheet"));
		sb.append("</style>\r");
		sb.append("</head>\r");
		sb.append("<body>\r");
		sb.append(get(map,"content"));
		sb.append("</body>\r");
		sb.append("</html>\r");
		return sb.toString();


	}
}
